import requests
import re
import matplotlib.pyplot as plt
from matplotlib import ticker
from matplotlib.pyplot import MultipleLocator
from PySide2.QtWidgets import QApplication, QMainWindow, QPushButton,  QPlainTextEdit,QLineEdit
from lxml import etree
from utils import*

app = QApplication([])

window = QMainWindow()
window.resize(500, 400)
window.move(300, 310)
window.setWindowTitle('GDP查询')

LineEdit_country = QLineEdit(window)
LineEdit_country.setPlaceholderText('请输入您想要查看的国家(中文）')
LineEdit_country.move(100, 25)
LineEdit_country.resize(300, 50)
LineEdit_country.setClearButtonEnabled(True)
# text_country = LineEdit_country.text()

LineEdit_start_year = QLineEdit(window)
LineEdit_start_year.setPlaceholderText('请输入您想查看的起始年龄（1990~2021）')
LineEdit_start_year.move(100, 125)
LineEdit_start_year.resize(300, 50)
LineEdit_start_year.setClearButtonEnabled(True)
# text_start_year = LineEdit_start_year.text()

LineEdit_end_year = QLineEdit(window)
LineEdit_end_year.setPlaceholderText('请输入您想查看的结束年龄（1990~2021）')
LineEdit_end_year.move(100, 225)
LineEdit_end_year.resize(300, 50)
LineEdit_end_year.setClearButtonEnabled(True)

button = QPushButton('check', window)
button.move(200, 325)
def is_Chinese(word):
    for ch in word:
        if '\u4e00' <= ch <= '\u9fff':
            return True
    return False
def handleCalc():
    text_country = LineEdit_country.text()
    text_start_year = LineEdit_start_year.text()
    text_end_year = LineEdit_end_year.text()
    if not is_Chinese(text_country) or int(text_start_year)<1975 or int(text_start_year)>2021 or int(text_end_year)<1975 or int(text_end_year)>2021 or int(text_end_year)<int(text_start_year):
        LineEdit_country.clear()
        LineEdit_country.setPlaceholderText('请重新输入（国家名需要是中文哦）')
        LineEdit_start_year.clear()
        LineEdit_start_year.setPlaceholderText('请重新输入（输入年段是1975~2021哦）')
        LineEdit_end_year.clear()
        LineEdit_end_year.setPlaceholderText('请重新输入（输入年段是1975~2021哦）')
    else:
        url = country[text_country]
        headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)'
                                 ' AppleWebKit/537.36 (HTML, like Gecko) Chrome/105.0.0.0 Safari/537.36 Edg/105.0.1343.53'}
        r = requests.get(url, headers=headers)
        html = etree.HTML(r.text)
        data_list = []
        sub1_data_list = []
        sub2_data_list = []
        sub3_data_list = []
        sub4_data_list = []
        u = parse(html, data_list)
        u.parse_data()
        # Extract the information for the year segment that the user wants to see
        for item in data_list:
            if text_end_year >= item['year'] >= text_start_year:
                sub1_data_list.append(item['GDP'])
                sub3_data_list.append(item['rate'])
        # Arrange the data in the direction of the growth of the number of years
        sub3_data_list = re.findall("\d+\.?\d*", ''.join(sub3_data_list[::-1]))
        for data in sub3_data_list:
            data = data * 100
        print(sub3_data_list)
        # GDP is extracted and arranged in the direction of annual growth
        for data in sub1_data_list[::-1]:
            sub2_data_list.append(re.findall(re.compile(r'[(](.*?)[)]', re.S), data))

        X_time = list(range(int(text_start_year), int(text_end_year)+1))   #x_time is abscissa
        Y_GDP = []
        Y_rate = sub3_data_list
        # sub2_data_list = sub2_data_list.split(',')[:-1]
        # print(sub2_data_list)
        for data in sub2_data_list:
            Y_GDP.append(int(''.join(data[0].split(',')))//100000000)  #Turns the read data into an actionable int type
        plt.figure(figsize=(100, 100))
        ax = plt.subplot(211)
        ax.plot(X_time, Y_GDP, 'r', label='weight changes', linewidth=3, color='r', marker='o', markerfacecolor='blue')
        x_major_locator = MultipleLocator(1)
        ax.xaxis.set_major_locator(x_major_locator) #turn x into 1debeishu
        ax.set_xlim(int(text_start_year), int(text_end_year))
        ax.set_title('GDP line chart')  # Line chart title
        ax.set_xlabel('time')  # The x-axis title
        ax.set_ylabel('GDP(a hundred million dollars)')  # Y-axis title
        for a, b in zip(X_time, Y_GDP):
            ax.text(a, b, b, ha='center', va='bottom', fontsize=10)
        ax = plt.subplot(212)
        ax.plot(X_time, Y_rate, 'r', label='weight changes', linewidth=3, color='r', marker='o', markerfacecolor='blue')
        ax.xaxis.set_major_locator(x_major_locator) #turn x into 1debeishu
        # y_major_locator = MultipleLocator(10)
        # ax.yaxis.set_major_locator(y_major_locator)
        ax.set_xlim(int(text_start_year), int(text_end_year))
        # ax.set_ylim(0, 20)
        ax.set_title('GDP rate in world line chart')  # Line chart title
        ax.set_xlabel('time')  # The x-axis title
        ax.set_ylabel('GDP rate(%)')  # Y-axis title
        for a, b in zip(X_time, Y_rate):
            ax.text(a, b, b, ha='center', va='bottom', fontsize=10)

        plt.show()
window.show()
button.clicked.connect(handleCalc)
app.exec_()


